using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

public class BaiduPanAuth {
    //进入 “控制台”→“百度网盘开放平台”→“创建应用”，填写应用名称、回调地址
    //（如http://localhost:8080/callback，本地测试用），获取API Key和Secret Key（后续授权需用到）。
    // 
    const string ApiKey = "你的API Key";
    const string SecretKey = "你的Secret Key";
    const string RedirectUri = "http://localhost:8080/callback"; // 与应用设置一致

    // 生成授权URL，引导用户跳转
    public string GetAuthorizationUrl() {
        return $"https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id={ApiKey}&redirect_uri={Uri.EscapeDataString(RedirectUri)}&scope=basic,netdisk&state=random_state";
    }

    // 用code换取Access Token
    public async Task<JObject> GetAccessToken(string code) {
        using (var httpClient = new HttpClient()) {
            var url = $"https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code={code}&client_id={ApiKey}&client_secret={SecretKey}&redirect_uri={Uri.EscapeDataString(RedirectUri)}";
            var response = await httpClient.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            return JObject.Parse(result); // 返回包含access_token、refresh_token等的JSON
        }
    }

    // 刷新Access Token（当token过期时）
    public async Task<JObject> RefreshAccessToken(string refreshToken) {
        using (var httpClient = new HttpClient()) {
            var url = $"https://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token={refreshToken}&client_id={ApiKey}&client_secret={SecretKey}";
            var response = await httpClient.GetAsync(url);
            var result = await response.Content.ReadAsStringAsync();
            return JObject.Parse(result);
        }
    }
}
